﻿using System;
using System.Security.Cryptography;
using System.Text;

namespace Mangdot.Webchat.Common
{
    public class Security
    {
        public static string EncryptToSHA1(string str)
        {
            SHA1CryptoServiceProvider sha1 = new SHA1CryptoServiceProvider();
            byte[] str1 = Encoding.UTF8.GetBytes(str);
            byte[] str2 = sha1.ComputeHash(str1);
            sha1.Clear();
            (sha1 as IDisposable).Dispose();
            return Convert.ToBase64String(str2);
        }

        public static string CleanGUID()
        {
            return System.Guid.NewGuid().ToString("N");
        }

        public static string RandomPassword()
        {
            StringBuilder builder = new StringBuilder();
            builder.Append(RandomString(4, true));
            builder.Append(RandomNumber(10, 99));
            builder.Append(RandomString(2, false));

            return builder.ToString();
        }

        public static string CreateSalt()
        {
            return System.Guid.NewGuid().ToString("N");
        }

        public  static string RandomString(int size, bool lowerCase)
        {
            StringBuilder builder = new StringBuilder();
            Random random = new Random((int)DateTime.UtcNow.Ticks);
            char ch;
            for (int i = 0; i < size; i++)
            {
                ch = Convert.ToChar(Convert.ToInt32(Math.Floor(26 * random.NextDouble() + 65)));
                builder.Append(ch);
            }
            if (lowerCase)
            {
                return builder.ToString().ToLower();
            }
            return builder.ToString();
        }

        private static int RandomNumber(int min, int max)
        {
            Random random = new Random((int)DateTime.UtcNow.Ticks);
            return random.Next(min, max);
        }

    }
}